package com.itheima.stock.algorithm;

import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;
import org.joda.time.DateTime;

import java.util.Collection;
import java.util.Date;
import java.util.stream.Collectors;

/**
 * @Description StockRtInfoTable范围匹配逻辑
 */
public class StockRtInfoTableRangeHandler implements RangeShardingAlgorithm<Date> {
    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Date> rangeShardingValue) {
        //获取逻辑表
        String logicTableName = rangeShardingValue.getLogicTableName();
        //获取片键
        String columnName = rangeShardingValue.getColumnName();
        //获取封装上限和下限的对象
        Range<Date> valueRange = rangeShardingValue.getValueRange();
        //判断是否有上限
        if (valueRange.hasLowerBound()) {
            //获取下限
            Date lowerEndpoint = valueRange.lowerEndpoint();
            //获取年月
            String startTime = new DateTime(lowerEndpoint).toString("yyyyMM");
            //过滤获取大于指定日期的值
            collection=collection.stream().filter(tbName->Integer.valueOf(tbName.substring(tbName.lastIndexOf("_")+1))>=Integer.valueOf(startTime)).collect(Collectors.toList());
        }
        if (valueRange.hasUpperBound()) {
            //获取上限
            Date upperEndpoint = valueRange.upperEndpoint();
            //获取年月
            String endTime = new DateTime(upperEndpoint).toString("yyyyMM");
            //过滤获取小于指定日期的值
            collection=collection.stream().filter(tbName->Integer.valueOf(tbName.substring(tbName.lastIndexOf("_")+1))<=Integer.valueOf(endTime)).collect(Collectors.toList());
        }
        return collection;
    }
}
